import { PROMISE } from 'oneutil'
import MobileDetect from 'mobile-detect'
import wx from '../wx'
let markerClusters;
let src;
let web_sw;
let web_ne;
export default {
  methods: {
    addCustomLayer_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_layerId = wx_object.layerId
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null

      PROMISE((SUCCESS, FAIL) => {
        if (!wx_layerId) {
          FAIL({
            errMsg: 'addGroundOverlay:err'
          })
          return
        }
        new TMap.ImageTileLayer.createCustomLayer({
          layerId: wx_layerId,
          map: this.map,
        }).then(customLayer => {
          if (customLayer) {
            const wx_res = {
              errMsg: 'addGroundOverlay:ok'
            }
            SUCCESS(wx_res)
          } else {
            FAIL({
              errMsg: 'addGroundOverlay:err'
            })
          }
        })
      }, wx_success, wx_fail, wx_complete)
    },

    addGroundOverlay_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_id = wx_object.id
      const wx_src = wx_object.src
      const wx_bounds = wx_object.bounds
      const wx_visible = wx_object.visible
      const wx_zIndex = wx_object.zIndex
      const wx_opacity = wx_object.opacity
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      //
      src = wx_src
      web_sw = new TMap.LatLng(wx_bounds.southwest.latitude, wx_bounds.southwest.longitude)
      web_ne = new TMap.LatLng(wx_bounds.northeast.latitude, wx_bounds.northeast.longitude)
      PROMISE((SUCCESS, FAIL) => {
        if (!wx_id || !wx_src || !wx_bounds) {
          FAIL({
            errMsg: 'addGroundOverlay:err'
          })
          return
        }
        new TMap.ImageGroundLayer({
          bounds: new TMap.LatLngBounds(web_sw, web_ne),
          src: wx_src,
          map: this.map,
          visible: wx_visible || true,
          zIndex: wx_zIndex || 1,
          opacity: wx_opacity || 1,
        })
        const wx_res = {
          errMsg: 'addGroundOverlay:ok'
        }
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    addMarkers_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_markers = wx_object.markers
      markerClusters = wx_markers
      const wx_clear = wx_object.clear
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS, FAIL) => {
        if (!wx_markers) {
          FAIL({
            errMsg: 'addMarkers:err'
          })
          return
        }
        this.markers_(wx_markers, wx_clear)
        const wx_res = {
          errMsg: 'addMarkers:ok'
        }
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    fromScreenLocation_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_x = wx_object.x
      const wx_y = wx_object.y
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS, FAIL) => {
        if (wx_x === null || !wx_y === null) {
          FAIL({
            errMsg: 'fromScreenLocation:err'
          })
          return
        }
        const wx_res = this.map.unprojectFromContainer(new TMap.Point(wx_x, wx_y))
        wx_res.errMsg = 'fromScreenLocation:ok'
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    getCenterLocation_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS) => {
        const wx_res = this.map.getCenter()
        wx_res.errMsg = 'getCenterLocation:ok'
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    getRegion_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS) => {
        const web_res = this.map.getBounds()
        const wx_res = {
          northeast: {
            latitude: web_res._ne.lat,
            longitude: web_res._ne.lng
          },
          southwest: {
            latitude: web_res._sw.lat,
            longitude: web_res._sw.lng
          },
          errMsg: 'getRegion:ok'
        }
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    getRotate_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS) => {
        const web_res = this.map.getRotation()
        const wx_res = {
          rotate: web_res,
          errMsg: 'getRotate:ok'
        }
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    getScale_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS) => {
        const web_res = this.map.getZoom()
        const wx_res = {
          scale: web_res,
          errMsg: 'getScale:ok'
        }
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    getSkew_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS) => {
        const web_res = this.map.getPitch()
        const wx_res = {
          skew: web_res,
          errMsg: 'getScale:ok'
        }
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    includePoints_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_points = wx_object.points
      const wx_padding = wx_object.padding
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS, FAIL) => {
        if (!wx_points) {
          FAIL({
            errMsg: 'includePoints:err'
          })
          return
        }
        this.includePoints_(wx_points, wx_padding)
        const wx_res = {
          errMsg: 'includePoints:ok'
        }
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    initMarkerCluster_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_enableDefaultStyle = wx_object.enableDefaultStyle
      const wx_zoomOnClick = wx_object.zoomOnClick
      const wx_gridSize = wx_object.gridSize
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS) => {
        new TMap.MarkerCluster({
          map: this.map,
          enableDefaultStyle: wx_enableDefaultStyle || true,
          zoomOnClick: wx_zoomOnClick || true,
          gridSize: wx_gridSize || 60,
          geometries: [{
            position: new TMap.LatLng(this.latitude, this.longitude)
          }],
        })
        const wx_res = {
          errMsg: 'initMarkerCluster:ok'
        }
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    moveAlong_(wx_object) {
      //编程没问题 测试有问题
      if (!wx_object) {
        return
      }
      const wx_markerId = wx_object.markerId
      const wx_path = wx_object.path
      const wx_autoRotate = wx_object.autoRotate
      const wx_duration = wx_object.duration
      const wx_success = wx_object.wx_success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS, FAIL) => {
        if (!wx_markerId || !wx_path || !wx_duration) {
          FAIL({
            errMsg: 'moveAlong:err'
          })
          return
        }
        const web_path = wx_path.map(path => {
          return new TMap.LatLng(path.latitude, path.longitude)
        })
        const object = {}
        object[wx_markerId] = {
          path: web_path,
          duration: wx_duration,
        }
        const web_MultiMarker = this.marker_(wx_markerId)
        // console.log(web_MultiMarker, object)
        web_MultiMarker.moveAlong(object, {
          autoRotation: wx_autoRotate || true
        })
        const wx_res = {
          errMsg: 'moveAlong:ok'
        }
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    moveToLocation_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_longitude = wx_object.longitude
      const wx_latitude = wx_object.latitude
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS) => {
        if (!this.showLocation) {
          return
        }
        if (wx_longitude && wx_latitude) {
          this.map.panTo(new TMap.LatLng(wx_longitude, wx_latitude))
        } else {
          navigator.geolocation.getCurrentPosition((position) => {
            this.map.panTo(new TMap.LatLng(position.coords.longitude, position.coords.latitude))
          })
        }
        const wx_res = {
          errMsg: 'moveToLocation:ok'
        }
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    on_(eventName, handlers) {
      if (!eventName && !handlers) {
        return
      }
      const wx_eventName = eventName
      const wx_handlers = handlers
      const wx_success = handlers.success
      const wx_fail = handlers.fail
      const wx_complete = handlers.complete
      eventName = null
      handlers = null
      PROMISE((SUCCESS) => {
        console.log(markerClusters)
        let web_geometries = markerClusters.map((markerCluster) => {
          if (markerCluster.joinCluster) {
            return {
              id: markerCluster.id,
              position: new TMap.LatLng(markerCluster.latitude, markerCluster.longitude)
            }
          }
        })
        const markerCluster = new TMap.MarkerCluster({
          id: 'cluster',
          map: this.map,
          enableDefaultStyle: true, // 启用默认样式
          minimumClusterSize: 2, // 形成聚合簇的最小个数
          geometries: web_geometries,
          zoomOnClick: true, // 点击簇时放大至簇内点分离
          gridSize: 60, // 聚合算法的可聚合距离
          averageCenter: false, // 每个聚和簇的中心是否应该是聚类中所有标记的平均值
          maxZoom: 10 // 采用聚合策略的最大缩放级别
        })
        const wx_res = markerCluster.on(wx_eventName, wx_handlers)
        wx_res.errMsg = 'on:ok'
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    openMapApp_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_longitude = wx_object.longitude
      const wx_latitude = wx_object.latitude
      const wx_destination = wx_object.destination
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS, FAIL) => {
        if (!wx_longitude || !wx_latitude || !wx_destination) {
          FAIL({
            errMsg: 'addGroundOverlay:err'
          })
          return
        }
        if (!this.showLocation) {
          return
        }
        navigator.geolocation.getCurrentPosition((position) => {
          const initposition = position.coords
          const md = new MobileDetect(navigator.userAgent)
          const os = md.os()
          let url
          switch (os) {
          case 'iOS':
            wx.showActionSheet({
              itemList: ['腾讯地图', '高德地图', '百度地图'],
              success(res) {
                console.log(res.tapIndex)
                switch (res.tapIndex) {
                case 0:
                  url = 'qqmap://map/routeplan?type=drive&fromcoord=' + initposition.latitude + ',' + initposition.longitude + '&to=' + wx_destination + '&tocoord=' + wx_latitude + ',' + wx_longitude + '&referer=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77';
                  break;
                case 1:
                  url = 'iosamap://navi?sourceApplication=amap&poiname=' + wx_destination + '&lat=' + wx_latitude + '&lon=' + wx_longitude + '&dev=1&style=0'
                  break;
                case 2:
                  url = 'baidumap://map/navi?location=' + wx_latitude + ',' + wx_longitude + '&src=ios.baidu.openAPIdemo&coord_type=gcj02'
                  break;
                default:
                  throw new Error(res.tapIndex);
                }
                console.log(res.tapIndex, url)
                window.open(url)
              },
              fail(res) {
                console.log(res.errMsg)
              }
            })
            break;
          case 'AndroidOS':
            wx.showActionSheet({
              itemList: ['腾讯地图', '高德地图', '百度地图'],
              success(res) {
                console.log(res.tapIndex)
                switch (res.tapIndex) {
                case 0:
                  url = 'qqmap://map/routeplan?type=drive&fromcoord=' + initposition.latitude + ',' + initposition.longitude + '&to=' + wx_destination + '&tocoord=' + wx_latitude + ',' + wx_longitude + '&referer=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77';
                  break;
                case 1:
                  url = 'androidamap://navi?sourceApplication=amap&poiname=' + wx_destination + '&lat=' + wx_latitude + '&lon=' + wx_longitude + '&dev=1&style=0'
                  break;
                case 2:
                  url = 'baidumap://map/navi?location=' + wx_latitude + ',' + wx_longitude + '&src=andr.baidu.openAPIdemo&coord_type=gcj02'
                  break;
                default:
                  throw new Error(res.tapIndex);
                }
                window.open(url)
              },
              fail(res) {
                console.log(res.errMsg)
              }
            })
            break;
          default:
            wx.showActionSheet({
              itemList: ['腾讯地图', '高德地图', '百度地图'],
              success(res) {
                switch (parseInt(res.tapIndex, 10)) {
                case 0:
                  url = 'https://apis.map.qq.com/uri/v1/routeplan?type=drive&fromcoord=' + initposition.latitude + ',' + initposition.longitude + '&to=' + wx_destination + '&tocoord=' + wx_latitude + ',' + wx_longitude + '&policy=0&referer=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77';
                  break;
                case 1:
                  url = 'https://uri.amap.com/navigation?from=' + initposition.longitude + ',' + initposition.latitude + ',startpoint&to=' + wx_longitude + ',' + wx_latitude + ',endpoint&coordinate=gaode'
                  break;
                case 2:
                  url = 'http://api.map.baidu.com/direction?origin=latlng:' + initposition.latitude + ',' + initposition.longitude + '&destination=latlng:' + wx_latitude + ',' + wx_longitude + '&mode=driving&output=html&coord_type=gcj02&src=webapp.baidu.openAPIdemo'
                  break;
                default:
                  throw new Error(res.tapIndex);
                }
                window.open(url)
              },
              fail(res) {
                console.log(res.errMsg)
              }
            })
            break;
          }
          const wx_res = {
            errMsg: 'openMapApp:ok'
          }
          SUCCESS(wx_res)
        });
        /*
        const geolocation = new qq.maps.Geolocation();
        const initposition = geolocation.getLocation((position) => {
          console.log(position)
          return position
        }, () => {
          console.error("定位失败");
        });
        */
        //1.

      }, wx_success, wx_fail, wx_complete)
    },

    removeCustomLayer_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_layerId = wx_object.layerId
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null

      PROMISE((SUCCESS, FAIL) => {
        if (!wx_layerId) {
          FAIL({
            errMsg: 'removeCustomLayer:err'
          })
          return
        }
        new TMap.ImageTileLayer.createCustomLayer({
          layerId: wx_layerId,
          map: this.map,
          visible: false,
          opacity: 0,
        }).then(customLayer => {
          if (customLayer) {
            const wx_res = {
              errMsg: 'removeCustomLayer:ok'
            }
            SUCCESS(wx_res)
          } else {
            FAIL({
              errMsg: 'removeGroundOverlay:err'
            })
          }
        })
      }, wx_success, wx_fail, wx_complete)
    },

    removeGroundOverlay_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_id = wx_object.id
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS, FAIL) => {
        if (!wx_id) {
          FAIL({
            errMsg: 'removeGroundOverlay:err'
          })
          return
        }
        new TMap.ImageGroundLayer({
          bounds: new TMap.LatLngBounds(web_sw, web_ne),
          src,
          map: this.map,
          visible: false,
          opacity: 0,
        })
        const wx_res = {
          errMsg: 'removeGroundOverlay:ok'
        }
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    removeMarkers_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_markerIds = wx_object.markerIds
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS, FAIL) => {
        if (!wx_markerIds) {
          FAIL({
            errMsg: 'removeMarkers:err'
          })
          return
        }
        wx_markerIds.forEach(wx_markerId => {
          this.marker_(wx_markerId)
        })
        const wx_res = {
          errMsg: 'removeMarkers:ok'
        }
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    setCenterOffset_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_offset = wx_object.offset
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS, FAIL) => {
        if (!wx_offset) {
          FAIL({
            errMsg: 'setCenterOffset:err'
          })
          return
        }
        this.map.setOffset({ x: wx_offset[0] * 320, y: wx_offset[1] * 400})
        const wx_res = {
          errMsg: 'setCenterOffset:ok'
        }
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    toScreenLocation_(wx_object) {
      if (!wx_object) {
        return
      }
      const wx_latitude = wx_object.latitude
      const wx_longitude = wx_object.longitude
      const wx_success = wx_object.success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS, FAIL) => {
        if (!wx_latitude || !wx_longitude) {
          FAIL({
            errMsg: 'toScreenLocation:err'
          })
          return
        }
        const wx_res = this.map.projectToContainer(new TMap.LatLng(wx_latitude, wx_longitude))
        wx_res.errMsg = 'toScreenLocation:ok'
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    translateMarker_(wx_object) {
      //编程没问题 测试有问题
      if (!wx_object) {
        return
      }
      const wx_markerId = wx_object.markerId
      const wx_destination = wx_object.destination
      const wx_autoRotate = wx_object.autoRotate
      const wx_rotate = wx_object.rotate
      const wx_duration = wx_object.duration
      const wx_animationEnd = wx_object.animationEnd
      const wx_success = wx_object.wx_success
      const wx_fail = wx_object.fail
      const wx_complete = wx_object.complete
      wx_object = null
      PROMISE((SUCCESS, FAIL) => {
        if (!wx_markerId || !wx_destination || !wx_autoRotate || !wx_rotate) {
          FAIL({
            errMsg: 'moveAlong:err'
          })
          return
        }
        const web_destination = new TMap.LatLng(wx_destination.latitude, wx_destination.longitude)
        const object = {}
        object[wx_markerId] = {
          path: web_destination,
          duration: wx_duration,
        }
        const web_MultiMarker = this.marker_(wx_markerId)
        // console.log(web_MultiMarker, object)
        web_MultiMarker.moveAlong(object, {
          autoRotation: wx_autoRotate || true,
          rotate: wx_rotate || 0,
        })
        web_MultiMarker.on('move_ended',wx_animationEnd)
        const wx_res = {
          errMsg: 'moveAlong:ok'
        }
        SUCCESS(wx_res)
      }, wx_success, wx_fail, wx_complete)
    },

    updateGroundOverlay_(wx_object) {
      this.addGroundOverlay_(wx_object)
    }
  }
}
